import { Injectable } from '@nestjs/common';

interface Room {
  players: Set<string>;
  puzzleState: any;
  image: string | null;
  difficulty: number;
}

@Injectable()
export class GameService {
  private rooms: Map<string, Room> = new Map();

  createRoom(roomId: string): Room {
    const room: Room = {
      players: new Set(),
      puzzleState: null,
      image: null,
      difficulty: 3,
    };
    this.rooms.set(roomId, room);
    return room;
  }

  getRoom(roomId: string): Room | undefined {
    return this.rooms.get(roomId);
  }

  joinRoom(roomId: string, playerId: string): Room {
    let room = this.rooms.get(roomId);
    if (!room) {
      room = this.createRoom(roomId);
    }
    room.players.add(playerId);
    return room;
  }

  leaveRoom(roomId: string, playerId: string): void {
    const room = this.rooms.get(roomId);
    if (room) {
      room.players.delete(playerId);
      if (room.players.size === 0) {
        this.rooms.delete(roomId);
      }
    }
  }

  updatePuzzleState(
    roomId: string,
    puzzleState: any,
    image: string | null,
    difficulty: number,
  ): void {
    const room = this.rooms.get(roomId);
    if (room) {
      room.puzzleState = puzzleState;
      if (image) room.image = image;
      room.difficulty = difficulty;
    }
  }

  getRoomState(roomId: string) {
    const room = this.rooms.get(roomId);
    if (!room) return null;

    return {
      players: Array.from(room.players),
      puzzleState: room.puzzleState,
      image: room.image,
      difficulty: room.difficulty,
    };
  }
}
